﻿using System.Data.Objects.SqlClient;
using System.Linq;
using Pyramid.Models;
using Pyramid.Security;

namespace Pyramid.Bll
{
	public class AdminCenterHelper : BllBase
	{
		public static AdminCenterHelper NewInstance
		{
			get { return new AdminCenterHelper(); }
		}

		public IQueryable<AdminCenter> GetList(AdminCenterQueryModel model, CustomPrincipal user)
		{
			var centers = Db.AdminCenters.Include("MarketZone").Where(x => x.CreateUserId == user.UserId);
			if (!string.IsNullOrWhiteSpace(model.AdminCenterCode))
			{
				centers = centers.Where(x => x.Code.Contains(model.AdminCenterCode));
			}
			if (!string.IsNullOrWhiteSpace(model.Keywords))
			{
				centers = centers.Where(x => x.Name.Contains(model.Keywords));
			}
			if (model.MarketZoneId.HasValue)
			{
				centers = centers.Where(x => x.ZoneId == model.MarketZoneId);
			}
			if (model.EstablishDateFrom.HasValue)
			{
				centers = centers.Where(x => SqlFunctions.DateDiff("d", model.EstablishDateFrom.Value, x.EstablishDate) >= 0);
			}
			if (model.EstablishDateTo.HasValue)
			{
				centers = centers.Where(x => SqlFunctions.DateDiff("d", model.EstablishDateTo.Value, x.EstablishDate) <= 0);
			}
			return centers;
		}

		public AdminCenter GetAdminCenter(int adminCenterId)
		{
			return Db.AdminCenters.Single(x => x.Id == adminCenterId);
		}
	}
}